//
//  HotSearchViewController.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/8.
//

import UIKit
import SnapKit

class HotSearchViewController: BaseViewController {

    private lazy var historyLists = [String]()
    private lazy var guessLists = [String]()
    private lazy var hotLists = [String]()
    private lazy var collectionView = UICollectionView()
    private lazy var tableView = UITableView()
    private var textField:UITextField?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        creatNav()
        headerView()
        createTableViewUI()
        loadData()
    }
    
    func creatNav(){
        let topNavView = UIView()
        topNavView.theme_backgroundColor = "Colors.navBar.backgroundColor"
        self.view.addSubview(topNavView)
        topNavView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Nav_HEIGHT)
        }
        
        let cancelBtn = UIButton.init(type: .custom).then {
            $0.titleLabel?.font = .systemFont(ofSize: 14)
            $0.setTitle("取消", for: .normal)
            $0.theme_setTitleColor("Colors.normalTextColor", forState: .normal)
            $0.addTarget(self, action: #selector(returnBack), for: .touchUpInside)
        }
        topNavView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.width.height.equalTo(40)
            make.bottom.equalToSuperview().offset(-3)
        }
        
        textField = UITextField.init().then {
            $0.theme_backgroundColor = "Colors.backgroundColor"
            $0.font = .systemFont(ofSize: 14)
            $0.placeholder = "请输入"
            $0.theme_tintColor = "Colors.highlightTextColor"
            $0.delegate = self
        }
        topNavView.addSubview(textField!)
        textField?.leftViewWithImage(image: "Icons.searchImage",
                                     size: CGSize(width: 19, height: 19))
        textField?.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.centerY.equalTo(cancelBtn.snp.centerY)
            make.height.equalTo(30)
            make.right.equalTo(cancelBtn.snp.left).offset(-10)
        }
        textField?.layercornerRadius(cornerRadius: 15)
        
        textField?.becomeFirstResponder()
    }
    
  
    
    func headerView () {
        let flowLayout = RPCustomTagFlowLayout.init()
        flowLayout.delegate = self
        collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(RPTagCell.self, forCellWithReuseIdentifier: NSStringFromClass(RPTagCell.self))
        collectionView.register(RPSearchTitleView.self,
                                forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                                withReuseIdentifier: NSStringFromClass(RPSearchTitleView.self))
        self.view.addSubview(collectionView)
        
        collectionView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 200)
    }
    
    func createTableViewUI() {
        tableView = UITableView.init(frame:CGRect.zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.theme_separatorColor = "Colors.separatorColor"
        tableView.tableFooterView = UIView()
        tableView.showsVerticalScrollIndicator = false
        tableView.keyboardDismissMode = .onDrag
        tableView.register(RPSearchLabelCell.self,
                           forCellReuseIdentifier: NSStringFromClass(RPSearchLabelCell.self))
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(Nav_HEIGHT)
        }
    }
    
    func loadData()  {
        let object = UserDefaults.standard.stringArray(forKey: kHostSearchCacheKey)
        if object != nil {
            historyLists = object!
        }
        guessLists = ["鬼王大人",
                      "seventeen壁纸",
                      "高级小众情头",
                      "小猫咪不听话会变成拖鞋"]
        collectionView.reloadData()
        hotLists = ["谁还不是个岛主千金",
                    "冬季斩男穿搭",
                    "洋葱乳酪风格摇摇薯测评",
                    "神秘组织外卖射手",
                    "这里是长白山仙境",
                    "证件照可以多好看",
                    "如有撞脸纯属巧合"]
        tableView.reloadData()
    }
    
}

@objc extension HotSearchViewController {
    
     func returnBack() {
        //我不理解 可能是因为MLeaksFinder对于textField没那么友好
        UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: textField, for: nil)
        if (self.presentedViewController != nil) {
            self.dismiss(animated: true, completion: nil)
        }else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func searchKeyword(_ keywords:String) {
        if !historyLists.contains(keywords) {
            historyLists.append(keywords)
            UserDefaults.standard.set(historyLists, forKey: kHostSearchCacheKey)
            collectionView.reloadData()
        }
    }
    
    func deleteHistory() {
        UserDefaults.standard.removeObject(forKey: kHostSearchCacheKey)
        historyLists.removeAll()
        collectionView.reloadData()
    }
    
}

extension HotSearchViewController:UICollectionViewDelegate,
                                  UICollectionViewDataSource,
                                  UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        if historyLists.count > 0 && guessLists.count > 0 {
            return 2
        }else if (historyLists.count > 0 || guessLists.count > 0) {
            return 1
        }else{
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if historyLists.count > 0 && section == 0 {
            return historyLists.count
        }
        return guessLists.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let dataArray = (historyLists.count > 0 && indexPath.section == 0) ? historyLists : guessLists
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(RPTagCell.self), for: indexPath) as! RPTagCell
        cell.tagLabel.text = dataArray[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let dataArray = (historyLists.count > 0 && indexPath.section == 0) ? historyLists : guessLists
        let size =  CustomTools.calculateTextSize(dataArray[indexPath.item], size: CGSize(width: 200, height: 20), font: .systemFont(ofSize: 13))
        return CGSize(width: size.width + 20, height: size.height+10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if historyLists.count > 0 || guessLists.count > 0 {
            return CGSize(width: collectionView.frame.width, height: 40)
        }
        return .zero
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
        if historyLists.count > 0 || guessLists.count > 0 {
            if kind == UICollectionView.elementKindSectionHeader{
                let v = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                                                                        withReuseIdentifier: NSStringFromClass(RPSearchTitleView.self),
                                                                        for: indexPath as IndexPath) as! RPSearchTitleView
                v.titleLabel.text = (historyLists.count > 0 && indexPath.section == 0) ? "历史记录" : "猜你想搜"
                v.deleBtn.isHidden = (historyLists.count > 0 && indexPath.section == 0) ? false : true
                if !v.deleBtn.isHidden {
                    v.deleBtn.addTarget(self, action: #selector(deleteHistory), for: .touchUpInside)
                }
                return v
            }
        }
        return UICollectionReusableView.init()
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dataArray = (historyLists.count > 0 && indexPath.section == 0) ? historyLists : guessLists
        searchKeyword(dataArray[indexPath.item])
    }
}

extension HotSearchViewController:UITableViewDelegate,
                                  UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return hotLists.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(RPSearchLabelCell.self),
                                                 for: indexPath) as! RPSearchLabelCell
        cell.setText(hotLists[indexPath.row], andIndexPath: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        searchKeyword(hotLists[indexPath.row])
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if hotLists.count == 0 {
            return nil
        }
        let xxx = RPSearchTitleView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 40))
        xxx.titleLabel.text = "搜索发现"
//        xxx.titleLabel.textColor = .init(patternImage: UIImage(gradientColors: [.init(hexString: "FFB367"),RPColor.redWine])!)//渐变色
        xxx.deleBtn.isHidden = true
        return xxx
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if hotLists.count == 0 {
            return 0
        }
        return 40
    }
}

extension HotSearchViewController:RPCustomTagFlowLayoutDelegate {
    func getCollectionVIewHeight(H: CGFloat) {
        collectionView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height:collectionView.collectionViewLayout.collectionViewContentSize.height)
        tableView.tableHeaderView = collectionView
    }
}

extension HotSearchViewController:UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.text?.count != 0 {
            searchKeyword(textField.text!)
            return textField.resignFirstResponder()
        }
        return false
    }
}
